'''
Created on Apr 19, 2009

@author: Administrator
'''
from django.contrib import auth
from django.forms import forms
from django.shortcuts import get_object_or_404
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from com.ericyang.common.web.middleware import threadlocals
from com.ericyang.common.web import redirect, page404, response
from com.ericyang.groupshopping.company.models import  Company
from com.ericyang.groupshopping.company.forms import CompanyCreationForm, CompanyChangeForm


# view company
@login_required
def view_company(request):
    user = threadlocals.get_current_user()
    # if not company user ,redirect to user page
    if user.is_common_user():
         return redirect("/user/")
    try:
        company = Company.objects.get(user__id=user.id)
        return response('company/company_view.html', {'company':company})
    except Company.DoesNotExist:
       return redirect("/company/new/")
    
    
# create company
@login_required
def create_company(request):
    user = threadlocals.get_current_user()
    if user.is_common_user():
         return redirect("/user/")
     
    if request.method == 'POST':
        form = CompanyCreationForm(request.POST)
        if form.is_valid():
            company = form.save()
            return redirect("/company/")
    else :
        form = CompanyCreationForm()
    
    return response('company/company_edit.html', {'form':form})

# edit comanpy
@login_required
def edit_company(request):
    user = threadlocals.get_current_user()
    if user.is_common_user():
         return redirect("/user/")
    
    try:
        company = Company.objects.get(user__id=user.id)
        if request.method == 'POST':
            form = CompanyChangeForm(company, request.POST)
            if form.is_valid():
                company = form.save()
                return redirect("/company/")
        else :
                # form = CompanyChangeForm(company)
            form = CompanyChangeForm(company, company.get_properties_tuple())
            
        return response('company/company_edit.html', {'form':form})
    except Company.DoesNotExist:
       return redirect("/company/new/")



#====================================================================
# list companies
@login_required
def delete_company(request, company_id):
    company = get_object_or_404(Company, pk=company_id)
    
    # temperialy not support company delete
    #company.delete()
    
    return response('company/company_list.html', {'companies':companies})

# list companies
@login_required
def list_company(request):
    companies = Company.objects.all()
    return response('company/company_list.html', {'companies':companies})

